import wepy from 'wepy'

export default class Home extends wepy.mixin {
  data = {
    // 获取商品列表数据参数
    queryData: {
      query: '',
      cid: '',
      pagenum: 1,
      pagesize: 10
    },
    // 商品列表数据
    goods: [],
    // 总条数
    total: 0,
    // 暂无图片
    none: 'http://destiny001.gitee.io/image/none.png',
    // 是否正在加载
    isLoading: false,
    // 是否隐藏 没有更多数据
    isOver: true
  }

  methods = {
    // 跳转商品详情
    goDetail (goods_id) {
      wepy.navigateTo({
        url: '/pages/goods_detail/main?goods_id='+goods_id
      })
    }
  }

  // 获取商品列表数据
  async getGoodsList (fn) {
    this.isLoading = true
    const { data: res } = await wepy.get('/goods/search', this.queryData)
    if(res.meta.status !== 200) {
      wepy.baseToast()
      fn && fn()
      return 
    }
    this.goods = [...this.goods,...res.message.goods]
    this.total = res.message.total
    this.isLoading = false
    fn && fn()
    this.$apply()
  }

  onLoad (options) {
    this.queryData.cid = options.cat_id?options.cat_id: ''
    this.queryData.query = options.query?options.query: ''
    this.getGoodsList()
  }

  // 监听上拉触底
  onReachBottom () {
    // 如果正在加载下一页的数据 就阻止再次发送请求
    if(this.isLoading) return
    if(this.queryData.pagenum*this.queryData.pagesize>=this.total){
      return this.isOver = false
    }
    this.queryData.pagenum++
    this.getGoodsList()
  }

  // 监听下拉刷新
  onPullDownRefresh () {
    this.queryData.pagenum = 1
    this.goods = []
    this.isOver = true
    this.getGoodsList(function(){
      wepy.stopPullDownRefresh()
    })
    
  }
}